package com.panfeng.xcloud.boss.provider.member.security.verifyCode;

import com.panfeng.xcloud.boss.provider.member.cache.CacheContext;
import com.panfeng.xcloud.boss.provider.member.security.SecurityConstants;
import com.panfeng.xcloud.common.core.configuration.DataDictionaryConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 *
 * 短信验证配置
 *
 * @author xiaobo
 * @version 1.0
 * @since 2018-12-28
 */
@Component
public class VerifyCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

	@Autowired
	private UserDetailsService userDetailsService;

	@Autowired
	private CacheContext cacheContext;

	@Autowired
	private VerifyCodeAuthenticationFailureHandler verifyCodeAuthenticationFailureHandler;

	@Autowired
	private VerifyCodeAuthenticationSuccessHandler verifyCodeAuthenticationSuccessHandler;

	@Autowired
	private DataDictionaryConfig dataDictionaryConfig;

	@Override
	public void configure(HttpSecurity http) {
		VerifyCodeAuthenticationFilter verifyCodeAuthenticationFilter = new VerifyCodeAuthenticationFilter();

		verifyCodeAuthenticationFilter.setMobileParameter(SecurityConstants.DEFAULT_PARAMETER_NAME_MOBILE);
		verifyCodeAuthenticationFilter.setVerifyCodeParameter(SecurityConstants.DEFAULT_PARAMETER_NAME_VERIFYCODE);
		verifyCodeAuthenticationFilter.setClientIdParameter(SecurityConstants.DEFAULT_PARAMETER_NAME_CLIENTID);
		verifyCodeAuthenticationFilter.setClientSecretParameter(SecurityConstants.DEFAULT_PARAMETER_NAME_CLIENTSECRET);
		verifyCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
		verifyCodeAuthenticationFilter.setAuthenticationSuccessHandler(verifyCodeAuthenticationSuccessHandler);
		verifyCodeAuthenticationFilter.setAuthenticationFailureHandler(verifyCodeAuthenticationFailureHandler);

		VerifyCodeAuthenticationProvider verifyCodeAuthenticationProvider = new VerifyCodeAuthenticationProvider();

		verifyCodeAuthenticationProvider.setUserDetailsService(userDetailsService);
		verifyCodeAuthenticationProvider.setCacheContext(cacheContext);
		verifyCodeAuthenticationProvider.setDataDictionaryConfig(dataDictionaryConfig);

		http.authenticationProvider(verifyCodeAuthenticationProvider)
				.addFilterAfter(verifyCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
	}

}
